/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.text.SimpleDateFormat;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;


public class DAOUser {
    static DAOUser instancia = null;
    
    SimpleDateFormat sdf;
    
    private DAOUser() {
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    } 
    
    public void crear(Usuario u) throws ErrorCreacionUser {
        EntityManager em = GestorPersistencia.instancia().getEntityManager();

        try {
            em.getTransaction().begin();
            em.persist(u);
            em.getTransaction().commit();
        }
        catch(EntityExistsException e) {
            if (em.getTransaction().isActive()) 
                em.getTransaction().rollback();
            throw new ErrorCreacionUser();
        }
    }
    
    public Usuario buscarPorEmail(String email) {
        EntityManager em = GestorPersistencia.instancia().getEntityManager();

        return em.find(Usuario.class, email);
       
        
    }


    public void actualizar(Usuario u) throws ErrorActualizacionUser {
        EntityManager em = GestorPersistencia.instancia().getEntityManager();

        try {
            em.getTransaction().begin();
            em.merge(u);
            em.getTransaction().commit();
        }
        catch(EntityExistsException e) {
            em.getTransaction().rollback();
            throw new ErrorActualizacionUser();
        }        
    }
    
    public void borrar(Usuario u) throws ErrorBorradoUser {
        EntityManager em = GestorPersistencia.instancia().getEntityManager();

        try {
            em.getTransaction().begin();
            em.remove(u);
            em.getTransaction().commit();
        }
        catch(EntityExistsException e) {
            em.getTransaction().rollback();
            throw new ErrorBorradoUser();
        }        
    }
    
    public static DAOUser instancia() {
        if (instancia == null) {
            instancia = new DAOUser();
        }
        
        return instancia;
    }
}